<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="8"
          ><div class="grid-content bg-purple">
            <el-input v-model="queryInfo.query" clearable>
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUserList()"
              ></el-button>
            </el-input></div
        ></el-col>
        <el-col :span="8"
          ><div class="grid-content bg-purple">
            <el-button type="primary" @click="dialogVisible = true"
              >添加用户</el-button
            >
          </div></el-col
        >
      </el-row>
      <el-table border style="width: 100%" :data="userList" class="el-table">
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180"
        ></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="" label="状态" width="58px">
          <el-switch
            v-model="value"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-table-column>
        <el-table-column prop="" label="操作">
          <template v-slot="scope">
            <!-- 作用域插槽 -->
            <!-- 修改按钮 -->
            <el-tooltip
              effect="dark"
              content="修改角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showUpdateDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip
              effect="dark"
              content="删除角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteUserInfo(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userList.pagenum"
        :page-sizes="[1, 3, 5, 6]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="20"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框组件  -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="30%"
      @close="dialogClose('addFormRef')"
    >
      <el-form
        label-width="100px"
        :model="addForm"
        ref="addFormRef"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser('addFormRef')"
          >添加</el-button
        >
      </div>
    </el-dialog>
    <!-- 修改用户信息对话框组件 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="updatedialogVisible"
      width="30%"
      @close="dialogClose('addFormRef')"
    >
      <el-form
        label-width="100px"
        :model="updatedForm"
        ref="addFormRef"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updatedForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updatedForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="updatedForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updatedUserInfo">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      queryInfo: {
        //关键字参数
        query: "",
        //当前页数
        pagenum: "1",
        //每页多少条
        pagesize: 4,
      },
      //对应id的用户信息
      userInfo: {},
      userList: [],
      value: true,
      currentPage1: 5,
      //添加对话框是否显示
      dialogVisible: false,
      //修改用户信息对话框是否显示
      updatedialogVisible: false,

      //添加用户
      addForm: {
        username: "",
        password: "",
        email: "",
        phone: "",
      },
      updatedForm: {},
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在3到8位之间", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 8, message: "长度在3到8位之间", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { min: 3, max: 8, message: "长度在3到8位之间", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { min: 3, max: 8, message: "长度在3到8位之间", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      console.log(res);
      if (res.meta.status != 200) this.$message.error("获取管理员列表失败");
      this.$message.success("获取管理员列表成功");
      this.userList = res.data.users;
    },
    //监听pagesize的事件
    handleSizeChange(pagesize) {
      console.log(`每页 ${pagesize} 条`);
      this.queryInfo.pagesize = pagesize;
      this.getUserList();
    },
    //监听页码值改变事件
    handleCurrentChange(pagenum) {
      console.log(`当前页: ${pagenum}`);
      this.queryInfo.pagenum = pagenum;
      this.getUserList();
    },
    //关闭时重置添加表单
    dialogClose(addFromRef) {
      this.$refs[addFromRef].resetFields();
    },
    //添加新用户
    addUser(addFormRef) {
      this.$refs[addFormRef].validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status !== 201) {
          return this.$message.error("用户添加失败");
        }
        this.dialogVisible = false;
        this.getUserList();
        return this.$message.success("用户添加成功");
      });
    },
    //显示修改对话框
    async showUpdateDialog(id) {
      this.updatedialogVisible = true;
      const { data: res } = await this.$http.get("users/" + id);
      this.updatedForm = res.data;
      if (res.meta.status != 200) return this.$message.error("获取列表失败");
      return this.$message.success("获取列表成功");
    },
    //提交修改用户信息
    async updatedUserInfo() {
      const { data: res } = await this.$http.put(
        "users/" + this.updatedForm.id,
        this.updatedForm
      );
      if (res.meta.status != 200) {
        this.$message.error("更新用户信息失败");
      }
      this.updatedialogVisible = false;
      this.getUserList();
      this.$message.success("更新用户信息成功");
    },

    async deleteUserInfo(id) {
      this.deletedialogVisible = true;
      const confirmRusult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "永久删除该用户",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(confirmRusult);
      // 用户点击了删除,则返回字符串 confirm
      // 用户取消了删除,则返回字符串 cancel
      if (confirmRusult !== "confirm") {
        return this.$message.info("已经取消了删除");
      }
      this.$http.delete("users/" + id).then((res) => {
        const { data: response } = res;
        // console.log(response);
        if (response.meta.status !== 200) {
          return this.$message.error("该用户删除失败");
        }
        this.$message.success("该用户已经删除");
        this.getUserList();
      });
    },
  },
  created() {
    this.getUserList();
  },
};
</script>

<style scoped>
.box-card {
  margin-top: 20px;
  width: 100%;
}
.el-table {
  margin-top: 20px;
}
</style>